Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Testnets #116

Merged
merged 2 commits into from
Oct 28, 2024
Merged

Testnets #116

merged 2 commits into from
Oct 28, 2024

Conversation

martillansky
Copy link
Contributor

@martillansky martillansky commented Oct 28, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new function to sanitize registration data, improving the accuracy of registration handling across supported chains.
  • Improvements

    • Streamlined the handling of vouches and enhanced error handling for data fetching.
    • Improved readability and organization of the Request component's code, maintaining its core functionality.

martillansky and others added 2 commits October 28, 2024 12:44
…ation

Profiles keep both registrations from issue on legacy subgraph

Pending fix on subgraph

This is a temporary workaround for fixing the issue at front-end
fix: vouch icon does not show due to legacy subgraph issue on registr…
Copy link

coderabbitai bot commented Oct 28, 2024

Walkthrough

The changes involve a significant reorganization of imports and minor adjustments in the page.tsx file, enhancing code clarity and maintainability without altering core functionality. Additionally, a new function sanitizeRegistration has been introduced in src/data/claimer.ts to improve the handling of registrations by ensuring only the most relevant registration is retained based on resolutionTime. The existing getClaimerData function has been updated to incorporate this new sanitization step.

Changes

File Path Change Summary
src/app/[pohid]/[chain]/[request]/page.tsx Restructured imports for better organization; minor adjustments to prepareVouchData and hasExpired functions for clarity; rendering logic remains intact.
src/data/claimer.ts Added sanitizeRegistration function to manage registration data; modified getClaimerData to call sanitizeRegistration after aggregating results.

Poem

In a world of code where bunnies hop,
Imports are tidy, no longer a flop.
With sanitizeRegistration, we clear the way,
For the best registrations to come out and play.
Hopping through logic, so crisp and bright,
Our code is now ready, a true delight! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Oct 28, 2024

Deploy Preview for proof-of-humanity-v2 ready!

Name Link
🔨 Latest commit e5dff7c
🔍 Latest deploy log https://app.netlify.com/sites/proof-of-humanity-v2/deploys/671fb29064d3020008b13a89
😎 Deploy Preview https://deploy-preview-116--proof-of-humanity-v2.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
src/app/[pohid]/[chain]/[request]/page.tsx (2)

Line range hint 89-111: Consider refactoring the hasExpired function

The function contains:

  1. Commented out code that should be either removed or uncommented
  2. Complex nested conditions that could be simplified

Consider breaking down the logic into smaller, more focused functions:

-  const hasExpired = () => {
+  const isResolvedRequestExpired = (request, contractData) => {
+    if (!request.revocation && request.humanity.winnerClaim.length > 0) {
+      if (request.humanity.winnerClaim[0].index === request.index) {
+        if (!!contractData.humanityLifespan) {
+          return !request.humanity.registration ||
+            Number(request.humanity.registration?.expirationTime) < Date.now() / 1000;
+        }
+      }
+    }
+    return true;
+  };
+
+  const isTransferringRequestExpired = (request, contractData) => {
+    return Number(request.creationTime) + Number(contractData.humanityLifespan) < Date.now() / 1000;
+  };
+
+  const hasExpired = () => {
     if (request.status.id === "resolved") {
-      if (!request.revocation && request.humanity.winnerClaim.length > 0) {
-        if (request.humanity.winnerClaim[0].index === request.index) {
-          if (!!contractData.humanityLifespan) {
-            return (
-              !request.humanity.registration ||
-              Number(request.humanity.registration?.expirationTime) <
-                Date.now() / 1000
-            );
-          }
-        } else return true;
-      }
+      return isResolvedRequestExpired(request, contractData);
     } else if (request.status.id === "transferring") {
-      return (
-        Number(request.creationTime) + Number(contractData.humanityLifespan) <
-        Date.now() / 1000
-      );
+      return isTransferringRequestExpired(request, contractData);
     }
     return true;
   };

Line range hint 146-201: Enhance error handling and type safety in prepareVouchData

The function could benefit from:

  1. More specific error handling
  2. Better separation of concerns
  3. Stronger type safety

Consider these improvements:

+ interface VouchChainData {
+   claimer?: {
+     id?: Address;
+     name?: string;
+     registration?: {
+       humanity: {
+         id?: Address;
+         winnerClaim: Array<{
+           evidenceGroup: {
+             evidence: Array<{ uri: string }>;
+           };
+         }>;
+       };
+     };
+   };
+ }

+ const getVoucherChainData = (
+   rawVouches: Record<SupportedChainId, ClaimerQuery>[],
+   chain: typeof supportedChains[number]
+ ): VouchChainData => {
+   const voucherEvidenceChain = supportedChains.find(
+     (chain) =>
+       rawVouches[chain.id].claimer &&
+       rawVouches[chain.id].claimer?.registration?.humanity.winnerClaim
+   );
+   const relevantChain = voucherEvidenceChain ?? chain;
+   return rawVouches[relevantChain.id];
+ };

  const prepareVouchData = async (
    rawVouches: Record<SupportedChainId, ClaimerQuery>[],
    isOnChain: boolean,
    skipStatusCheck: boolean,
  ): Promise<VouchData[]> => {
    return Promise.all(
      rawVouches.map(async (rawVoucher) => {
        const out: VouchData = {
          voucher: undefined,
          name: undefined,
          pohId: undefined,
          photo: undefined,
          vouchStatus: undefined,
          isOnChain,
        };

        try {
-         const voucherEvidenceChain = supportedChains.find(
-           (chain) =>
-             rawVoucher[chain.id].claimer &&
-             rawVoucher[chain.id].claimer?.registration?.humanity.winnerClaim,
-         );
-         const relevantChain = !!voucherEvidenceChain
-           ? voucherEvidenceChain
-           : chain;
+         const chainData = getVoucherChainData(rawVoucher, chain);
+         const { claimer } = chainData;

-         out.name = rawVoucher[relevantChain.id].claimer?.name;
-         out.voucher = rawVoucher[relevantChain.id].claimer?.id;
+         out.name = claimer?.name;
+         out.voucher = claimer?.id;
+         out.pohId = claimer?.registration?.humanity.id ?? out.voucher;

-         out.pohId =
-           rawVoucher[relevantChain.id].claimer?.registration?.humanity.id;
-         if (!out.pohId) out.pohId = out.voucher;

          if (!skipStatusCheck) {
            out.vouchStatus = isOnChain
              ? isValidOnChainVouch(
                  request.claimer.vouchesReceived.find(
                    (v) => v.from.id === out.voucher!,
                  )! as VouchQuery,
                )
              : await isValidVouch(
                  chain.id,
                  out.voucher!,
                  offChainVouches.find(
                    (vouch) => vouch.voucher === out.voucher,
                  )?.expiration,
                );
          }

-         const uri = rawVoucher[
-           relevantChain.id
-         ].claimer?.registration?.humanity.winnerClaim
-           .at(0)
-           ?.evidenceGroup.evidence.at(0)?.uri;
+         const uri = claimer?.registration?.humanity.winnerClaim
+           .at(0)
+           ?.evidenceGroup.evidence.at(0)
+           ?.uri;

          if (!uri) return out;

          const evFile = await ipfsFetch<EvidenceFile>(uri);
          if (!evFile?.fileURI) return out;

          const regFile = await ipfsFetch<RegistrationFile>(evFile.fileURI);
          out.photo = regFile.photo;
          
          return out;
-       } catch {
+       } catch (error) {
+         console.error('Error preparing vouch data:', error);
          return out;
        }
      }),
    );
  };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4e0e36c and e5dff7c.

📒 Files selected for processing (2)
  • src/app/[pohid]/[chain]/[request]/page.tsx (1 hunks)
  • src/data/claimer.ts (2 hunks)
🔇 Additional comments (4)
src/data/claimer.ts (2)

8-28: ⚠️ Potential issue

Several improvements needed in the sanitization function.

The function has several areas that could be improved for better maintainability and reliability:

  1. The function mutates its input parameter without documenting this behavior
  2. Using map for side effects is an antipattern
  3. Using var instead of let is outdated
  4. The nested conditionals make the logic harder to follow

Consider this refactored version:

 // This fixes an error in the legacy subgraph were registration has not
 // been removed as expected. Once solved the issue at subgraph level this
 // function should be removed
+/**
+ * @param res - Record of claimer queries by chain ID
+ * @description Mutates the input parameter to fix legacy subgraph registration issues
+ */
 const sanitizeRegistration = (res: Record<SupportedChainId, ClaimerQuery>) => {
-  var regChain: SupportedChainId | undefined = undefined;
+  let regChain: SupportedChainId | undefined = undefined;
-  supportedChains.map((chain) => {
+  supportedChains.forEach((chain) => {
     if (!regChain && res[chain.id].claimer?.registration) regChain = chain.id;
     else if (regChain && res[chain.id].claimer?.registration) {
+      const currentTime = res[chain.id].claimer?.registration?.humanity.winnerClaim.at(0)?.resolutionTime;
+      const regChainTime = res[regChain].claimer?.registration?.humanity.winnerClaim.at(0)?.resolutionTime;
+      
+      if (!currentTime || !regChainTime) return;
+      
       if (
-        res[regChain].claimer?.registration?.humanity.winnerClaim.at(0)
-          ?.resolutionTime >
-        res[chain.id].claimer?.registration?.humanity.winnerClaim.at(0)
-          ?.resolutionTime
+        regChainTime > currentTime
       ) {
         res[chain.id].claimer!.registration = null;
       } else {

Let's verify the usage of this temporary fix:

#!/bin/bash
# Check if there are any TODOs or related comments about subgraph fixes
rg -i "subgraph.*fix|fix.*subgraph" --type ts

Line range hint 8-41: Verify if this fix affects both testnet and mainnet.

Since this PR is related to testnets, we should verify if this subgraph fix is needed for both testnet and mainnet environments.

Let's check for environment-specific code:

✅ Verification successful

Let me gather more information about the chain configurations and supported chains to better understand the scope of this fix.


Based on the gathered information, I can now provide a final response:

The fix is needed for both mainnet and testnet environments

The sanitization fix is required across all environments because:

  1. The code comment explicitly states it's fixing a legacy subgraph issue that needs to be addressed at the subgraph level
  2. The implementation in sanitizeRegistration is environment-agnostic and works with any supported chains
  3. The same code is present in both mainnet and testnet configurations, as seen in the chain configurations (chains.mainnets.ts and chains.testnets.ts)
  4. The subgraph URLs in config/subgraph.ts show this affects both mainnet and testnet deployments
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for environment-specific handling in chain configurations
rg -A 5 "mainnet|testnet" --type ts

# Check the subgraph configurations
rg -A 5 "subgraph.*url|url.*subgraph" --type ts

Length of output: 2342


Script:

#!/bin/bash
# Check chain configurations and supported chains
rg -A 5 "supportedChains" --type ts

# Check for any environment-specific handling in the claimer data
rg -A 5 "sanitizeRegistration|sanitizeClaimerData" --type ts

# Look for any chain-specific logic in the codebase
ast-grep --pattern 'const mainnet = { $$$, id: $_ }'

Length of output: 28316

src/app/[pohid]/[chain]/[request]/page.tsx (2)

1-30: LGTM! Well-organized imports

The imports are now logically grouped and well-organized, improving code readability.


Line range hint 203-458: Improve performance and accessibility in the UI rendering

Several improvements could enhance the component:

  1. Async operations in rendering could cause performance issues
  2. Some images lack proper alt text
  3. Accessibility attributes could be enhanced

Consider these improvements:

  1. Move data preparation to a separate hook or server action:
// hooks/useVouchData.ts
export const useVouchData = (vouches: Array<any>) => {
  const [vouchData, setVouchData] = useState<VouchData[]>([]);
  
  useEffect(() => {
    const prepareData = async () => {
      const data = await prepareVouchData(vouches, true, true);
      setVouchData(data);
    };
    prepareData();
  }, [vouches]);
  
  return vouchData;
};
  1. Add proper alt text and ARIA labels:
  <Image
-   alt="image"
+   alt={`Profile photo of ${registrationFile?.name || 'user'}`}
    src={ipfs(registrationFile.photo)}
    width={144}
    height={144}
  />

  <video
    className="w-full"
+   aria-label="Registration video"
    src={ipfs(registrationFile.video)}
    controls
  />
  1. Add proper heading structure and ARIA landmarks:
- <div className="content mx-auto flex w-[84vw] max-w-[1500px]">
+ <main className="content mx-auto flex w-[84vw] max-w-[1500px]" role="main">
    <h1 className="sr-only">Request Details</h1>
    ...
- </div>
+ </main>

Let's verify the accessibility issues:

Comment on lines +40 to 41
sanitizeRegistration(out);
return await sanitizeClaimerData(out, id);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider error handling for sanitization step.

The integration of sanitizeRegistration looks correct, but consider adding error handling to prevent issues from propagating.

Consider wrapping the sanitization in a try-catch:

-  sanitizeRegistration(out);
+  try {
+    sanitizeRegistration(out);
+  } catch (error) {
+    console.error('Failed to sanitize registration data:', error);
+    // Still proceed with sanitizeClaimerData as the original data might be usable
+  }
   return await sanitizeClaimerData(out, id);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
sanitizeRegistration(out);
return await sanitizeClaimerData(out, id);
try {
sanitizeRegistration(out);
} catch (error) {
console.error('Failed to sanitize registration data:', error);
// Still proceed with sanitizeClaimerData as the original data might be usable
}
return await sanitizeClaimerData(out, id);

@martillansky martillansky merged commit 74a011b into master Oct 28, 2024
7 checks passed
This was referenced Oct 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant